﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;
using VB.BusinessLogic.Models;
using VB.Entries.SQLManager;
using DBDataContext = VB.Entries.DataModel.VBBlogModelDataContext;
using DBArticle = VB.Entries.DataModel.Article;

namespace VB.BusinessLogic.Services
{
    public class ArticleService
    {       
        public static ArticleService Istance
        {
            get 
            {
                return new ArticleService();
            }
        }

        public List<Article> GetTopNewArticles(Int32 quantity)
        {
            using (ConnectionContext c = SqlManager.GetConnectionContext())
            {
                using (DBDataContext dc = c.CreateContext())
                {
                    var articles = dc.Articles.Where(a => a.IsDraft == false).OrderByDescending(a => a.DatePosted).Take(quantity);
                    return ConvertToBusinessModel(articles).ToList();
                }
            }
        }

        public Article GetArticleByAlias(String alias)
        {
            using (ConnectionContext c = SqlManager.GetConnectionContext())
            {
                using (DBDataContext dc = c.CreateContext())
                {
                    var article = dc.Articles.FirstOrDefault(a => a.Alias.Equals(alias));
                    if (article != null)
                    {
                        return new Article(article);
                    }
                    return null;
                }
            }
        }

        private IEnumerable<Article> ConvertToBusinessModel(IQueryable<DBArticle> articles)
        {
            foreach (DBArticle a in articles)
            {
                yield return new Article(a);
            }
        }
    }
}
